#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Copyright © 启明星辰 版权所有
# @Time    : 2024/5/13 15:18
# @Author  : 胡浩浩
# @File    : docker_tools.py
# @IDE     : PyCharm
# @description :
import os
import time
from typing import Tuple, Any

import docker

client = docker.from_env()


def start_mitmproxy_container(listen_port: int = 8180, web_port: int = 8081, filter_express: str = None) -> tuple[
    Any, Any]:
    # Docker 客户端连接

    # 容器配置
    container_config = {
        'image': 'ptesting_mitmproxy',  # 镜像名称
        'command': [
            'mitmweb',
            '-s', 'mitmproxy_plugin.py',
            '--set', 'ssl_insecure=true',
            '--listen-host', '0.0.0.0',
            '--listen-port', f'{listen_port}',
            '--web-host', '0.0.0.0',
            '--web-port', f'{web_port}',
            '--set',
            r'view_filter=!.css & !.js & !.png & !.icon & !.ttf & !.svg & !.jpg & !192.168.114.37' if not filter_express else r'view_filter=!.css & !.js & !.png & !.icon & !.ttf & !.svg & !.jpg & !192.168.114.37 & {0}'.format(
                (filter_express,))
        ],
        'ports': {f'{listen_port}/tcp': listen_port, f'{web_port}/tcp': web_port},
        'detach': True,
        'tty': True
    }

    # 启动容器
    container = client.containers.run(**container_config)

    container = client.containers.get(container.id)
    container_ip = container.attrs['NetworkSettings']['Networks']['bridge']['IPAddress']
    # 返回容器 ID
    return container.id, container_ip


def stop_and_restart_docker_container(container_id, container_ip, filter_express=None):
    try:
        # 停止容器
        container = client.containers.get(container_id)
        print(f"Container {container_id} stopped successfully.")
        # 复制文件到容器内指定目录
        with open("../src/mitmproxy_plugin_temp.py", 'rb') as f:
            data = f.read().decode('utf-8')
            data = data.replace("{{filter_express}}", filter_express).replace("{{container_ip}}", container_ip)
            print(data)
        with open("../src/source/mitmproxy_plugin.py", 'wb') as f:
            f.write(data.encode('utf-8'))
        # 重启容器
        # 构建 docker cp 命令
        docker_cp_command = f"docker cp mitmproxy_plugin.py {container_id}:/home/mitmproxy"

        # 使用 os.system 执行命令
        os.system(docker_cp_command)
        print(f"File 'mitmproxy_plugin_temp.py' copied to container '{container_id}' successfully.")
        container.start()
        print("File copied successfully and container restarted.")
        return True
    except docker.errors.NotFound as e:
        print(f"Container {container_id} not found: {e}")
        return False
    except docker.errors.APIError as e:
        print(f"Error stopping or removing container {container_id}: {e}")
        return False



if __name__ == "__main__":
    # container_id,container_ip = start_mitmproxy_container()
    # print("已启动的容器 ID：", container_id)
    # print("已启动的容器 IP：", container_ip)
    stop_and_restart_docker_container("f916514909c8","172.17.0.8","10.11")
    # 启动docker服务后需要获取docker实例的ip信息
